<?php
namespace App\Api;

use App\Model\ELEVENACTIVITY;
use App\Model\WALLETIOC;
use PhalApi\Api;
use App\Common\WalletBase;
use App\Model\WALLETADDRESS;
use App\Model\WALLETTRADE;
use App\Model\WALLET;
use PhalApi\Exception\BadRequestException;


class WalletTask extends Api
{
    CONST OFFICIALADDRESS = '0xc875d24eeb806df5320d08294a8fc3d5facd4a4f';          //官方钱包地址
    CONST OFFICIALUSERID = '100014';                         //官方钱包uid
    CONST USERID = '22020';                              //系统uid
    // 定时扫描每个用户 每个币的充值记录 并更新trade表
    public function getRules()
    {
        return
            [
                'Wheel' => [
                    'token' => ['name' => 'token', 'require' => true],
                    'num' => ['name' => 'num', 'require' => true],
                    'ico' => ['name' => 'ico', 'require' => true],
                ],
            ];
    }
    public function recharge()
    {
        $model = new WALLETADDRESS();
        $trade = new WALLETTRADE();
        $wallet = $model->getAllWallet();
        foreach($wallet as $v)
        {
            $recharge = WalletBase::depositLogs($v['wallet_userid']);

            if(!empty($recharge->deposits))
            {
                //var_dump($recharge->deposits);die;
                $count = $trade->getCounts($v['uid']);
                $deposite = array_reverse($recharge->deposits);
                foreach($deposite as $k => $s)
                {
                    if($k + 1 > $count)
                    {
                        $data = WalletBase::accounts($v['wallet_userid']);
                        $tobalance = 0;

                        foreach($data->spotAccounts as $a)
                        {
                            if($a->currency == $s->currency && $a->type == 'SPOT_AVAILABLE')
                            {
                                $tobalance = $a->balance;
                                break;
                            }
                        }
                        $insert['type'] = 1;
                        $insert['num'] = $s->amount;
                        $insert['touid'] = $v['uid'];
                        $insert['ico'] = $s->currency;
                        $insert['tobalance'] = $tobalance;
                        //$insert['fromaddress'] = self::OFFICIALADDRESS;
                        $insert['toaddress'] = $v['wallet_address'];
                        $insert['style'] = 2;
                        $insert['create_time'] = substr($s->createdAt, 0, 10);
                        $trade->insert($insert);
                    }
                }
            }
        }
    }

    /**
     * 从交易所抓取币的价格
     */
    public function curlPrice()
    {
        $model = new WALLETIOC();
        $url = $model->getUrl();
        $arr = [];
        foreach($url as $v)
        {
            $content = file_get_contents($v['url_forprice']);
            $pattern = "/<div class=coinprice>(.*?)<span class=tags-red>/is";
            preg_match($pattern, $content, $info);
            if(empty($info))
            {
                $pattern = "/<div class=coinprice>(.*?)<span class=tags-green>/is";
                preg_match($pattern, $content, $info);
            }
            if(empty($info))
            {
                return false;
            }

            $price = ltrim($info[1], '￥');
            $price = str_replace(",","",$price);
            $arr[$v['ico']] =  $price;
            $v['price'] = $price;
            $v['update_time'] = time();
            $model->update($v['id'], $v);
        }
        /**
         * 双十一活动
         */
        $eleven = new ELEVENACTIVITY();
        $all = $eleven->getAll();
        foreach($all as $v)
        {
            if(array_key_exists($v['ico'], $arr))
            {
                $v['price'] = $arr[$v['ico']];
                $eleven->update($v['id'], $v);
            }
        }
        
    }

    /**
     * 大转盘提供接口
     */

    public function Wheel()
    {
        $model = new WALLETADDRESS();
        $ico = new WALLETIOC();
        $data = $model->getWalletByToken($this->token);
        $ico = $ico->getIoc($this->ico);
        if(!$ico)
            throw new BadRequestException('这个币不存在');

        /**
         * 获取余额
         */

        $accounts = WalletBase::accounts(self::OFFICIALUSERID);
        $balance = $eth = 0;
        foreach($accounts->spotAccounts as $k => $v)
        {
            if($v->currency == $this->ico && $v->type == 'SPOT_AVAILABLE')
            {
                $balance = $v->balance;
            }
        }

        if($balance < $this->num)
        {
            throw new BadRequestException('余额不足');
        }

        $account = WalletBase::accounts($data['wallet_userid']);
        $tobalance = 0;
        foreach($account->spotAccounts as $k => $v)
        {
            if($v->currency == $this->ico && $v->type == 'SPOT_AVAILABLE')
            {
                $tobalance = $v->balance;
            }
        }

        $transfer = WalletBase::transfer($this->num, $this->ico, self::OFFICIALUSERID, $data['wallet_userid']);

        if(!empty($transfer->from->id))
        {
            \PhalApi\DI()->logger->info('{大转盘},用户id:'.$data['uid'].',交易成功;数量:'.$this->num.',币种:'.$this->ico);
            $trade = new WALLETTRADE();
            $insert = [];
            $insert['type'] = 4;            //大转盘
            $insert['balance'] = $balance - $this->num;
            $insert['tobalance'] = $tobalance + $this->num;
            $insert['num'] = $this->num;
            $insert['fromuid'] = self::USERID;
            $insert['touid'] = $data['uid'];
            $insert['ico'] = $this->ico;
            $insert['fromaddress'] = self::OFFICIALADDRESS;
            $insert['toaddress'] = $data['wallet_address'];
            $insert['style'] = 1;               //内部转账
            $insert['create_time'] = time();
            $trade->insert($insert);
            return [true, 'msg' => '交易成功'];
        }
        \PhalApi\DI()->logger->error('{大转盘},用户id:'.$data['uid'].',交易失败:'.$transfer->message);
        throw new BadRequestException('交易失败');
    }

    public function sets()
    {
        $data = WALLET::sets();
        foreach($data as $v)
        {
            $token = WALLET::DDTT($v['token']);
            $wallet = WALLET::wallet($token[0]['id']);
            if($wallet)
            {
                WALLET::up($token[1]['id'], $wallet['id']);
            }
            WALLET::ups($token[0]['id'], $v['token'].'1');
        }

    }

}